package com.eduhzy.ttw.work.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.annotation.ScopeType;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.commonsdk.entity.MineClassData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.work.R;
import com.eduhzy.ttw.work.R2;
import com.eduhzy.ttw.work.di.component.DaggerPublishWorkComponent;
import com.eduhzy.ttw.work.di.module.PublishWorkModule;
import com.eduhzy.ttw.work.mvp.contract.PublishWorkContract;
import com.eduhzy.ttw.work.mvp.model.entity.WorkSubmitData;
import com.eduhzy.ttw.work.mvp.presenter.PublishWorkPresenter;
import com.eduhzy.ttw.work.mvp.ui.adapter.WorkUploadAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-3 10:07:39
 */
@Route(path = RouterHub.WORK_PUBLISHWORKACTIVITY)
public class PublishWorkActivity extends BaseActivity<PublishWorkPresenter> implements PublishWorkContract.View {

    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.et_title)
    EditText mEtTitle;
    @BindView(R2.id.et_content)
    EditText mEtContent;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.tv_pic)
    QMUIAlphaTextView mTvPic;
    @BindView(R2.id.tv_audio)
    QMUIAlphaTextView mTvAudio;
    @BindView(R2.id.tv_video)
    QMUIAlphaTextView mTvVideo;
    @BindView(R2.id.tv_time)
    TextView mTvTime;
    @BindView(R2.id.rv_list_class)
    RecyclerView mRvListClass;
    @BindView(R2.id.switch_online)
    Switch mSwitchOnline;
    @BindView(R2.id.btn_submit)
    QMUIRoundButton mBtnSubmit;

    @Inject
    WorkUploadAdapter mAdapter;
    @Inject
    BaseQuickAdapter<MineClassData, AutoBaseViewHolder> mClassAdapter;
    @Inject
    @ScopeType()
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    @ScopeType(2)
    RecyclerView.LayoutManager mClassLayoutManager;
    @Inject
    List<WorkSubmitData> lists;
    private int mMimeType;
    private int mMaxSelectNum = 8;
    private int mSelectionMode = PictureConfig.MULTIPLE;
    private List<LocalMedia> selectList = new ArrayList<>();
    private StringBuilder classIds;
    private List<String> classes = new ArrayList<>();
    private SimpleDateFormat mFormat;
    private TimePickerView pvTime;
    private Calendar deTime;
    private Calendar mCalendar;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerPublishWorkComponent
                .builder()
                .appComponent(appComponent)
                .publishWorkModule(new PublishWorkModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.work_activity_publish_work;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCalendar = Calendar.getInstance();
        mEtTitle.setText(TimeUtils.date2String(mCalendar.getTime(),new SimpleDateFormat("MM月dd日作业")));
        mPresenter.getClassByUser();
        mBtnSubmit.setChangeAlphaWhenPress(true);
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(mLayoutManager);
        mRvListClass.setAdapter(mClassAdapter);
        mRvListClass.setLayoutManager(mClassLayoutManager);
        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(3, 20, false);
        mRvListClass.addItemDecoration(decoration);
        mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        deTime = Calendar.getInstance();
        deTime.set(Calendar.HOUR_OF_DAY, 8);
        deTime.set(Calendar.MINUTE, 30);
        deTime.add(Calendar.DATE, 1);
        mTvTime.setText(TimeUtils.millis2String(deTime.getTimeInMillis(), mFormat));
        initListener();
    }

    @Override
    public void getClassData(List<MineClassData> list) {
        mClassAdapter.setNewData(list);
    }

    private void initListener() {
        mClassAdapter.setOnItemClickListener((adapter, view, position) -> {
            MineClassData mineClassData = mClassAdapter.getData().get(position);
            mineClassData.setSelect(!mineClassData.isSelect());
            mClassAdapter.notifyItemChanged(position);
            if (mineClassData.isSelect()) {
                classes.add(mineClassData.getId());
            } else {
                classes.remove(mineClassData.getId());
            }
        });

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            WorkSubmitData data = lists.get(position);
            if (data.isUploading()) {
                showMessage("上传完成后才可操作");
                return;
            }

            int mimeType = data.getLocalMedia().getMimeType();
            if (mimeType == PictureMimeType.ofVideo()) {
                // 预览视频
                if (ObjectUtils.isEmpty(data.getUrl())) {
                    showMessage("视频转换中，请稍后");
                    return;
                }
                PictureSelector.create(getActivity()).externalPictureVideo(data.getLocalMedia().getPath());
            } else if (mimeType == PictureMimeType.ofImage()) {
                List<LocalMedia> lists = new ArrayList<>();
                for (WorkSubmitData workSubmitData : mAdapter.getData()) {
                    if (workSubmitData.getLocalMedia().getMimeType() == PictureMimeType.ofImage()) {
                        lists.add(workSubmitData.getLocalMedia());
                    }
                }

                PictureSelector.create(getActivity()).themeStyle(R.style.public_picture_white_style).openExternalPreview(lists.indexOf(mAdapter.getData().get(position).getLocalMedia()), lists);
            } else if (mimeType == PictureMimeType.ofAudio()) {
                if (ObjectUtils.isEmpty(data.getUrl())) {
                    showMessage("音频转换中，请稍后");
                    return;
                }
                PictureSelector.create(getActivity()).externalPictureAudio(data.getLocalMedia().getPath());
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (lists.get(position).isUploading()) {
                showMessage("上传完成后才可操作");
                return;
            }
            mAdapter.getData().remove(position);
            mAdapter.notifyDataSetChanged();
        });

    }

    @Override
    public void showLoading() {
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {
        mEmptyView.hide();
    }

    @OnClick(R2.id.layout_time)
    public void onLayoutTimeClicked() {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
            return;
        }
        if (ObjectUtils.isEmpty(pvTime)) {

            Calendar startDate = Calendar.getInstance();
            Calendar endDate = Calendar.getInstance();
            endDate.add(Calendar.MONTH, 1);
            pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                deTime.setTime(date);
                mTvTime.setText(TimeUtils.millis2String(deTime.getTimeInMillis(), mFormat));
            })
                    .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                    .setCancelText("取消")//取消按钮文字
                    .setSubmitText("确定")//确认按钮文字
                    .setTitleSize(20)//标题文字大小
                    .setTitleText("截止时间")//标题文字
                    .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                    .setDate(deTime)// 如果不设置的话，默认是系统时间*/
                    .setRangDate(startDate, endDate)//起始终止年月日设定
                    .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .isDialog(true)//是否显示为对话框样式
                    .build()
            ;
        }
        pvTime.show();
    }

    @OnClick(R2.id.btn_submit)
    public void onViewClicked() {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
        } else {
            StringBuilder imageIds = null;
            StringBuilder audioIds = null;
            StringBuilder videoIds = null;
            if (ObjectUtils.isNotEmpty(lists)) {
                for (WorkSubmitData data : lists) {
                    int mimeType = data.getLocalMedia().getMimeType();
                    if (mimeType == PictureMimeType.ofVideo()) {
                        if (ObjectUtils.isEmpty(videoIds)) {
                            videoIds = new StringBuilder();
                        }
                        videoIds.append(data.getUploadId() + ",");
                    } else if (mimeType == PictureMimeType.ofImage()) {
                        if (ObjectUtils.isEmpty(imageIds)) {
                            imageIds = new StringBuilder();
                        }
                        imageIds.append(data.getUploadId() + ",");
                    } else if (mimeType == PictureMimeType.ofAudio()) {
                        if (ObjectUtils.isEmpty(audioIds)) {
                            audioIds = new StringBuilder();
                        }
                        audioIds.append(data.getUploadId() + ",");
                    }
                }
            }
            if (RxUtil.showEditTip(this, mEtTitle, "请输入标题")) {
                return;
            }
            String content = mEtContent.getText().toString();
            if (ObjectUtils.isEmpty(imageIds) && ObjectUtils.isEmpty(audioIds) && ObjectUtils.isEmpty(videoIds) && ObjectUtils.isEmpty(content)) {
                showMessage("作业内容不允许为空");
                return;
            }
            if (ObjectUtils.isEmpty(classes)) {
                showMessage("请选择发布班级");
                return;
            } else {
                classIds = new StringBuilder();
                for (String aClass : classes) {
                    classIds.append(aClass + ",");
                }
            }

            String title = mEtTitle.getText().toString();
            int online = mSwitchOnline.isChecked() ? 1 : 0;
            MobclickAgent.onEvent(getActivity(),"ttw_work_publish");
            mPresenter.create(title, content, imageIds, audioIds, videoIds, deTime.getTimeInMillis(), classIds, online);

        }
    }

    @OnClick({R2.id.tv_pic, R2.id.tv_audio, R2.id.tv_video})
    public void onViewClicked(View view) {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
            return;
        }
        int i = view.getId();
        if (i == R.id.tv_pic) {
            mMimeType = PictureMimeType.ofImage();
        } else if (i == R.id.tv_audio) {
            mMimeType = PictureMimeType.ofAudio();
        } else if (i == R.id.tv_video) {
            mMimeType = PictureMimeType.ofVideo();
        }
        PictureSelector.create(getActivity())
                .openGallery(mMimeType)
                .theme(R.style.public_picture_white_style)
                .maxSelectNum(mMaxSelectNum - lists.size())
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(mSelectionMode)
                .previewVideo(true)
                .previewImage(true)
                .enablePreviewAudio(true)
                .isCamera(true)
                .isZoomAnim(true)
                .synOrAsy(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void update() {
        Message msg = Message.obtain();
        msg.what = EventBusTags.WORK_PUBLISH_SUCCESS;
        EventBus.getDefault().post(msg, RouterHub.WORK_WORKHOMEFRAGMENT);
        killMyself();
    }

    @Override
    public void onBackPressed() {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
        } else {
            super.onBackPressed();
        }
    }

    @Subscriber(tag = RouterHub.WORK_PUBLISHWORKACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.START_UPLOAD:
                WorkSubmitData workSubmitData = (WorkSubmitData) msg.obj;
                if (!workSubmitData.isUploading() && !workSubmitData.isUploadComplete()) {
                    mPresenter.upload(workSubmitData);
                }
                break;
            case EventBusTags.END_UPLOAD:
                dealUploadFile();
                break;
            default:
        }
    }

    private void dealUploadFile() {
        if (ObjectUtils.isNotEmpty(selectList)) {
            LocalMedia remove = selectList.remove(0);
            lists.add(new WorkSubmitData().setLocalMedia(remove));
            mAdapter.notifyItemInserted(lists.size() - 1);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    dealUploadFile();
                    break;
                default:
            }
        }
    }

    private boolean isUploading() {
        if (!lists.isEmpty()) {
            for (WorkSubmitData list : lists) {
                if (list.isUploading()) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

}
